<template>
  <div class="login-groud">
    <div class="login-box">
      <div class="login-head">
        <div class="logo">
          <span v-html="$t('components.login.login.label7')"></span>
        </div>
        <div class="nav-list">
          <a href="">首页</a>
          <a href="">解决方案</a>
          <a href="">关于我们</a>
        </div>
      </div>
      <div class="banner">
        <div class="banner-images">
          <img src="../../assets/icon/login_bg.png">
        </div>
        <div class="login">
          <el-tabs v-model="defaultActiveName" type="border-card" @tab-click="clickTab">
            <el-tab-pane name="tab_pwd">
              <span slot="label"><i class="el-icon-key"></i>&nbsp;<span v-text="$t('components.login.login.label9')"></span></span>
              <el-form class="login-form" ref="loginModel1" :model="loginModel" :rules="rules" @submit.native.prevent
                :status-icon="statusIcon">
                <el-form-item prop="loginName" style="margin-bottom: 20px;margin-left:20px;width: 90%;">
                  <el-input placeholder="Account" v-model="loginModel.loginName" prefix-icon="el-icon-user" maxlength="36"
                    show-word-limit></el-input>
                </el-form-item>
                <el-form-item prop="password" style="margin-bottom: 20px;margin-left:20px;width: 90%">
                  <el-input placeholder="Password" v-model="loginModel.password" prefix-icon="el-icon-key" type="password"
                    maxlength="36" show-password></el-input>
                </el-form-item>
                <el-form-item prop="lang" style="margin-bottom: 40px;margin-left:20px;width: 90%">
                  <select class="form-control" @change="changeLang" v-model="loginModel.lang">
                    <option value="zh-CN">中文</option>
                    <option value="en-US">English</option>
                  </select>
                </el-form-item>
                <el-form-item style="margin-left:20px;width: 90%;">
                  <el-button type="primary" class="btn-block" @click="login()" v-html="$t('components.login.login.label4')"></el-button>
                  <el-row>&nbsp;</el-row>
                  <el-row>&nbsp;</el-row>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane name="tab_verification_code">
              <span slot="label"><i class="el-icon-message"></i>&nbsp;<span v-text="$t('components.login.login.label10')"></span></span>
              <el-form class="login-form" ref="loginModel2" :model="loginModel" :rules="rules" @submit.native.prevent
                :status-icon="statusIcon">
                <el-form-item prop="loginName" style="margin-bottom:20px;margin-left:20px;width: 90%;">
                  <el-input placeholder="Email or Mobile" v-model="loginModel.loginName" prefix-icon="el-icon-user"
                    maxlength="36" show-word-limit @input="loginNameChange"></el-input>
                </el-form-item>
                <el-form-item prop="verificationCode" style="margin-bottom: 20px;margin-left:20px;width: 90%">
                  <el-row>
                    <el-col :span="15">
                      <el-input placeholder="Verification Code" v-model="loginModel.verificationCode" maxlength="6"
                        show-word-limit></el-input>
                    </el-col>
                    <el-col :span="1">&nbsp;</el-col>
                    <el-col :span="6">
                      <el-button v-if="showGetverificationCodeButton" type="primary" v-html="$t('components.login.login.label8')"
                        @click="getverificationCode" :disabled="getverificationCodeButtonState"></el-button>
                      <el-button v-if="!showGetverificationCodeButton" type="primary" v-text="maxSecondsMsg" :disabled="true"></el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item prop="lang" style="margin-bottom: 40px;margin-left:20px;width: 90%">
                  <select class="form-control" @change="changeLang" v-model="loginModel.lang">
                    <option value="zh-CN">中文</option>
                    <option value="en-US">English</option>
                  </select>
                </el-form-item>
                <el-form-item style="margin-left:20px;width: 90%">
                  <el-button type="primary" class="btn-block" @click="login4verificationCode()" v-html="$t('components.login.login.label4')"></el-button>
                  <el-row>&nbsp;</el-row>
                  <el-row>&nbsp;</el-row>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane name="tab_qrcode">
              <span slot="label"><i class="el-icon-mobile-phone"></i>&nbsp;<span v-text="$t('components.login.login.label11')"></span></span>
              <div  style="margin-top:30px;padding-bottom: 104px;text-align: center;">
                <qrcode-vue v-loading="qrcodeLoading" :size="153" :value="qrText" :foreground="qrcodeBackground">
                </qrcode-vue>
                <p>
                  <el-link type="primary" @click="refreshQr()" :disabled="qrcodeLoading">换一张</el-link>
                </p>
                <p style="padding-top: 20px;color: #909399;"><span style="font-size: 12px;">手机扫码登录，安全又方便。扫描屏幕左侧下方下载App</span></p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="login-footer">
        <div class="QR-code">
          <div>
            <img src="../../assets/icon/official_public_number.png" width="191" height="191">
            <label>官方公众号</label>
          </div>
		  <div>
		    <img src="../../assets/icon/official_public_number.png" width="191" height="191">
		    <label>官方公众号</label>
		  </div>
		  <div>
		    <img src="../../assets/icon/official_public_number.png" width="191" height="191">
		    <label>官方公众号</label>
		  </div>
        </div>
        <div class="footer-info">
          <p v-html="$t('components.common.companyName')"></p>
          <p v-html="$t('components.common.rightDescription')"></p>
          <p v-html="$t('components.common.address')">
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import qrcodeVue from 'qrcode.vue'
import {
  uuid
} from 'vue-uuid'
import Stomp from 'stompjs'

export default {
  components: {
    qrcodeVue
  },
  name: 'login',
  data () {
    return {
      qrcodeLoading: true,
      getverificationCodeButtonState: true,
      showGetverificationCodeButton: true,
      maxSecondsMsg: '剩余60秒',
      statusIcon: true,
      loginModel: {
        loginName: '',
        password: '',
        verificationCode: '',
        lang: this.$i18n.locale
      },
      client: Stomp.client(Vue.$rabbitmqURL),
      loginType: 1,
      qrText: uuid.v1(),
      clientId: uuid.v1(),
      qrcodeBackground: 'black',
      defaultActiveName: 'tab_pwd',
      rules: {
        loginName: [{
          required: true,
          message: this.$t('components.login.login.msg1'),
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: this.$t('components.login.login.msg2'),
          trigger: 'blur'
        }],
        verificationCode: [{
          required: true,
          message: this.$t('components.login.login.msg3'),
          trigger: 'blur'
        }]
      }
    }
  },
  created: function () {
    if (this.loginType === 1) {
      let that = this
      document.onkeydown = function (e) {
        let key = window.event.keyCode
        if (key === 13) {
          that.login()
        }
      }
    } else if (this.loginType === 2) {
      let that = this
      document.onkeydown = function (e) {
        let key = window.event.keyCode
        if (key === 13) {
          that.login4verificationCode()
        }
      }
    }

    this.connect()
  },
  mounted: function () {},
  destroyed: function () {
    if (this.client != null) {
      console.info('页面销毁，申请断开连接')
      this.client.disconnect()
    }
  },
  methods: {
    connect: function () {
      const headers = {
        'login': Vue.$rabbitmqUserName,
        'passcode': Vue.$rabbitmqPassword,
        'host': Vue.$profilesActive,
        'heart-beat': '0,0'
      }
      this.client.connect(headers, this.onConnected, this.onFailed)
    },
    onConnected: function (frame) {
      console.log('MQ connected: ' + frame)
      // 订阅频道
      const topic = '/exchange/exchange-qrcodelogin4app2server/key-qrcodelogin4app2server'
      this.client.subscribe(topic, this.responseCallback, this.onFailed)
    },
    onFailed: function (frame) {
      console.log('MQ Failed: ' + frame)
    },
    responseCallback: function (frame) {
      console.log('MQ responseCallback：' + frame)
      if (!Vue.$isNullOrIsBlankOrIsUndefined(frame.body)) {
        let data = frame.body

        if (data.clientId === this.clientId) {
          const loading = this.$loading({
            lock: true,
            target: document.querySelector('.login'),
            text: '正在登陆...',
            background: 'rgba(0, 0, 0, 0.6)'
          })

          let appId = Vue.$appId
          let nonce = uuid.v1()
          let timestamp = new Date().getTime()
          let paramsStr = 'code=' + data.code + '&message=' + data.message + '&checkCodeRC4=' + data.checkCodeRC4
          let link = paramsStr + '&nonce=' + nonce + '&timestamp=' + timestamp
          let sign = Vue.$sign(link)
          Vue.$ajax({
            method: 'post',
            url: Vue.$adminServerURL + '/api/open/v1/WebUserLoginByQrCodeOpenApi?' + paramsStr,
            headers: {
              'Content-Type': 'application/json',
              'appId': appId,
              'sign': sign,
              'nonce': nonce,
              'timestamp': timestamp
            }
          }).then(res => {
            loading.close()
            if (res.data.flag === 'SUCCESS') {
              this.loginContext.setLoginContext(res)
              this.$router.push({
                path: '/Index'
              })
            } else {
              this.$message({
                message: res.data.message,
                type: 'warning'
              })
            }
          })
        }
        console.log(frame.body)
      } else {
        console.info('没有监听到扫码登录消息')
      }
    },
    login: function () {
      if (this.loginType !== 1) {
        return
      }
      this.$refs['loginModel1'].validate((valid) => {
        if (!valid) {} else {
          const loading = this.$loading({
            lock: true,
            target: document.querySelector('.login'),
            text: '正在登陆...',
            background: 'rgba(0, 0, 0, 0.6)'
          })

          let appId = Vue.$appId
          let nonce = uuid.v1()
          let timestamp = new Date().getTime()
          let paramsStr = 'loginName=' + this.loginModel.loginName + '&password=' + Vue.$md5(this.loginModel.password) + '&lang=' + this.loginModel.lang
          let link = paramsStr + '&nonce=' + nonce + '&timestamp=' + timestamp
          let sign = Vue.$sign(link)
          Vue.$ajax({
            method: 'post',
            url: Vue.$adminServerURL + '/api/open/v1/WebUserLoginByAccountOpenApi/login?' + paramsStr,
            headers: {
              'Content-Type': 'application/json',
              'appId': appId,
              'sign': sign,
              'nonce': nonce,
              'timestamp': timestamp
            }
          }).then(res => {
            loading.close()
            if (res.data.flag === 'SUCCESS') {
              this.loginContext.setLoginContext(res)
              this.$router.push({
                path: '/Index'
              })
            } else {
              this.$message({
                message: res.data.message,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    login4verificationCode: function () {
      if (this.loginType !== 2) {
        return
      }
      this.$refs['loginModel2'].validate((valid) => {
        if (!valid) {} else {
          const loading = this.$loading({
            lock: true,
            target: document.querySelector('.login'),
            text: '正在登陆...',
            background: 'rgba(0, 0, 0, 0.6)'
          })

          let appId = Vue.$appId
          let nonce = uuid.v1()
          let timestamp = new Date().getTime()
          let paramsStr = 'loginName=' + this.loginModel.loginName + '&verificationCode=' + this.loginModel.verificationCode + '&lang=' + this.loginModel.lang
          let link = paramsStr + '&nonce=' + nonce + '&timestamp=' + timestamp
          let sign = Vue.$sign(link)
          Vue.$ajax({
            method: 'post',
            url: Vue.$adminServerURL + '/api/open/v1/WebUserLoginByVerificationOpenApi?' + paramsStr,
            headers: {
              'Content-Type': 'application/json',
              'appId': appId,
              'sign': sign,
              'nonce': nonce,
              'timestamp': timestamp
            }
          }).then(res => {
            loading.close()
            if (res.data.flag === 'SUCCESS') {
              this.loginContext.setLoginContext(res)
              this.$router.push({
                path: '/Index'
              })
            } else {
              this.$message({
                message: res.data.message,
                type: 'warning'
              })
            }
          })
        }
      })
    },
    changeLang: function () {
      this.$i18n.locale = this.loginModel.lang // 如果不设置这个值，则需要刷新页面才看见效果
      localStorage.setItem('locale', this.loginModel.lang)

      this.rules.loginName = [{
        required: true,
        message: this.$t('components.login.login.msg1'),
        trigger: 'blur'
      }]
      this.rules.password = [{
        required: true,
        message: this.$t('components.login.login.msg2'),
        trigger: 'blur'
      }]
    },
    refreshQr: function () {
      this.qrcodeLoading = true

      let appId = Vue.$appId
      let nonce = uuid.v1()
      let timestamp = new Date().getTime()
      let paramsStr = 'clientId=' + this.clientId + '&lang=' + this.$i18n.locale
      let link = paramsStr + '&nonce=' + nonce + '&timestamp=' + timestamp
      let sign = Vue.$sign(link)
      Vue.$ajax({
        method: 'get',
        url: Vue.$adminServerURL + '/api/open/v1/WebUserLoginByQrCodeOpenApi/getAppLoginQRCode?' + paramsStr,
        headers: {
          'Content-Type': 'application/json',
          'appId': appId,
          'sign': sign,
          'nonce': nonce,
          'timestamp': timestamp
        }
      }).then(res => {
        this.qrcodeLoading = false
        if (res.data.flag === 'SUCCESS') {
          this.qrText = res.data.obj
        } else {
          this.$message({
            message: res.data.message,
            type: 'warning'
          })
        }
      })
    },
    getverificationCode: function () { // 获取验证码
      this.showGetverificationCodeButton = false // 隐藏获取验证码按钮、显示计时按钮
      let timing = 60
      let that = this
      let intervalId = setInterval(function () {
        if (timing === 0) {
          window.clearInterval(intervalId)
          that.showGetverificationCodeButton = true // 隐藏几十按钮、显示获取验证码按钮
        }
        that.maxSecondsMsg = '剩余' + timing + '秒'
        timing--
      }, 1000)

      let appId = Vue.$appId
      let nonce = uuid.v1()
      let timestamp = new Date().getTime()
      let paramsStr = 'loginName=' + this.loginModel.loginName + '&type=4'
      let link = paramsStr + '&nonce=' + nonce + '&timestamp=' + timestamp
      let sign = Vue.$sign(link)
      Vue.$ajax({
        method: 'get',
        url: Vue.$adminServerURL + '/api/open/v1/VerificationCodeOpenApi?' + paramsStr,
        headers: {
          'Content-Type': 'application/json',
          'appId': appId,
          'sign': sign,
          'nonce': nonce,
          'timestamp': timestamp
        }
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          this.$message({
            message: '验证码已经发送，请查收',
            type: 'success'
          })
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    loginNameChange: function () { // 切换登录方式
      if (!Vue.$isNullOrIsBlankOrIsUndefined(this.loginModel.loginName)) {
        this.getverificationCodeButtonState = false
      } else {
        this.getverificationCodeButtonState = true
      }
    },
    clickTab: function (tab) {
      if (tab.name === 'tab_pwd') {
        this.loginType = 1
      } else if (tab.name === 'tab_qrcode') {
        this.loginType = 3
        this.refreshQr()
      } else if (tab.name === 'tab_verification_code') {
        this.loginType = 2
      }
    }
  }
}
</script>

<style>
  @import "login.css";
</style>
